import socket
import struct

multicast_ip = "239.0.0.1"
multicast_port = 7789
INTERFACE_IP = '192.168.7.5'  # 指定网卡的IP地址

if __name__ == "__main__":
    # udp套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    # 运行套接字重用地址
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # 绑定 ip, 端口
    sock.bind((INTERFACE_IP, multicast_port))
    # 加入组播组
    group = socket.inet_aton(multicast_ip)
    mreq = struct.pack("4sL", group, socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    # 设置多播发送的网卡
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(INTERFACE_IP))

    # 接受组播数据
    try:
        while True:
            data, addr = sock.recvfrom(1024)
            print(f"接受到组播{addr} : {data.decode()}")
    except KeyboardInterrupt:
        print("退出程序")
    finally:
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, mreq)
        sock.close()
